/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license.txt -file, included in
 * the distribution.
 */

#include "rotationdata.h"
#include <QDebug>
#include <QRotationReading>


/*!
  \class RotationData
  \brief Manages the data received from the rotation sensor.
*/


/*!
  Constructor.
*/
RotationData::RotationData(QObject *parent /* = 0 */) :
    QObject(parent),
    m_rotationSensor(0),
    m_yRot(45.0f)
{
    m_rotationSensor = new QRotationSensor(this);
    QObject::connect(m_rotationSensor, SIGNAL(readingChanged()), SLOT(updateRotation()));
    m_rotationSensor->start();
}


/*!
  Interprets the received sensor reading.
*/
void RotationData::updateRotation()
{
    QRotationReading *reading = m_rotationSensor->reading();

    qreal yDiff = reading->y() - m_yRot;

    static bool xHysteresis = false;

    if (reading->x() < 5 && reading->x() > -5) {
        xHysteresis = false;
    }
    else if (reading->x() < -15 && !xHysteresis) {
        xHysteresis = true;
        emit tiltedLeft();
    }
    else if (reading->x() > 15 && !xHysteresis) {
        xHysteresis = true;
        emit tiltedRight();
    }

    // Lowpass filtering for the throttle
    m_yRot += 0.9f * yDiff;

    emit rotationChanged(QVariant(m_yRot));
}
